package com.lkd.job;

import com.aliyun.mns.common.utils.DateUtil;
import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class UserJob {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 每日工单量初始化
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception {
        log.info("接收到xxl-job的调度任务，任务参数：{}",param);
        //查询用户列表
        List<UserEntity> list = userService.list();
        //0代表生成今日数据，1代表生成次日数据，测试时参数输入0
        int plusDays = "0".equals(param)? 0 : 1;
        list.forEach(user ->{
            if (user.getRoleId().intValue() != 0) {
                String key = VMSystem.REGION_TASK_KEY_PREF
                          //获取时间
                        + LocalDate.now().plusDays(plusDays).format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                        //获取区域
                        + "." + user.getRegionId()
                        //获取角色
                        + "." + user.getRoleCode();
                redisTemplate.opsForZSet().add(key,user.getId(),0);
                redisTemplate.expire(key, Duration.ofDays(2));
            }
        });
        //构建数据
        return ReturnT.SUCCESS;
    }
}
